﻿using Common.AspNetCore;
using Common.Infrastructure;
using Log.Api.Extensions;
using Log.Api.IService;
using Log.Api.LogModels;
using Log.Api.QueryModel;
using Log.Api.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Nest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Log.Api.Service
{
    /// <summary>
    /// 设备参数记录，如老化设备的老化参数
    /// </summary>
    public class EquipmentParamLogService : CommonService
    {
        private IEsClientProviderService clientProvider;
        private string indexName = "minigroupageparamlog";
        private readonly IOptions<EsConfig> config;
        private readonly bool isSaveByHttp;

        /// <summary>
        /// 索引名称
        /// </summary
        public EquipmentParamLogService(IServiceProvider provider, IEsClientProviderService client, IConfiguration c, IOptions<EsConfig> config) : base(provider)
        {
            this.clientProvider = client;
            this.config = config;
            this.isSaveByHttp = LibSysUtils.ToBoolean(c["IsAddByHttp"]);
        }

        public ElasticClient GetClient()
        {
            return this.clientProvider.GetClient(indexName);
        }

        /// <summary>
        /// 批量插入
        /// </summary>
        public async Task<bool> InsertsAsync(List<EquipmentParamLogModel> model)
        {
            if (this.isSaveByHttp)
            {
                foreach (var item in model)
                {
                    await ElasticsearchUtils.SaveEquipmentParamLogAsync(this.config.Value.Urls[0], indexName, item);
                }

                return true;
            }
            else
            {
                var client = GetClient();
                var result = true;
                foreach (var item in model)
                {
                    var response = await client.CreateDocumentAsync(model);
                    if (!response.IsValid)
                    {
                        result = false;
                    }
                }

                return result;
            }
        }

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public long GetTotalCountByPage(EquipmentParamLogQuery query)
        {
            var client = GetClient();
            var response = client.Search<EquipmentParamLogModel>(s => s.Query(q => q.Match(w => w.Field(f => f.OrgId).Query(query.OrgId))
            && q.Match(w => w.Field(f => f.WorkCode).Query(query.WorkCode))
            && q.Match(w => w.Field(f => f.LineCode).Query(query.LineCode))
            && q.Match(w => w.Field(f => f.LineName).Query(query.LineName))
            && q.Match(w => w.Field(f => f.EquipmentCode).Query(query.EquipmentCode))
            && q.Match(w => w.Field(f => f.EquipmentType).Query(query.EquipmentType))
            && q.Match(w => w.Field(f => f.WorkstageCode).Query(query.WorkstageCode))
             && q.Match(w => w.Field(f => f.ApiKey).Query(query.ApiKey))
            && +q.DateRange(d => d.Field(f => f.CT).GreaterThanOrEquals(query.BeginTime).LessThan(query.EndTime))));
            return response.Total;
        }

        /// <summary>
        /// 根据条件获取日志
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<EquipmentParamLogModel> GetLogPage(EquipmentParamLogQuery query)
        {
            var client = GetClient();
            var response = client.Search<EquipmentParamLogModel>(s => s.Query(q => q.Match(w => w.Field(f => f.OrgId).Query(query.OrgId))
            && q.Match(w => w.Field(f => f.WorkCode).Query(query.WorkCode))
            && q.Match(w => w.Field(f => f.LineCode).Query(query.LineCode))
            && q.Match(w => w.Field(f => f.LineName).Query(query.LineName))
            && q.Match(w => w.Field(f => f.EquipmentCode).Query(query.EquipmentCode))
            && q.Match(w => w.Field(f => f.EquipmentType).Query(query.EquipmentType))
            && q.Match(w => w.Field(f => f.WorkstageCode).Query(query.WorkstageCode))
             && q.Match(w => w.Field(f => f.ApiKey).Query(query.ApiKey))
             && +q.DateRange(d => d.Field(f => f.CT).GreaterThanOrEquals(query.BeginTime).LessThan(query.EndTime))).Sort(s => s.Descending(d => d.CT)).From((query.PageIndex - 1) * query.PageSize).Take(query.PageSize));
            return response.Documents.ToList();
        }
    }
}
